package com.okaixz.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.client.mapper.KbUserAssistantInfoMapper;
import com.okaixz.client.model.domain.KbAssistant;
import com.okaixz.client.model.domain.KbCustomerAssistant;
import com.okaixz.client.model.domain.KbUserAssistantInfo;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.model.dto.KbUserAssistantAddAllDto;
import com.okaixz.client.service.IKbAssistantService;
import com.okaixz.client.service.IKbCustomerAssistantService;
import com.okaixz.client.service.IKbUserAssistantInfoService;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.constant.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-05-26
 */
@Service
public class KbUserAssistantInfoServiceImpl extends ServiceImpl<KbUserAssistantInfoMapper, KbUserAssistantInfo> implements IKbUserAssistantInfoService {

    @Autowired
    private IKbAssistantService kbAssistantService;
    @Autowired
    private IKbCustomerAssistantService customAssistantService;
    @Autowired
    private IUserService userService;

    @Override
    public List<KbUserAssistantInfo> getListbyUserId(String userId, Integer sex) {
        List<KbUserAssistantInfo> list = lambdaQuery()
                .eq(KbUserAssistantInfo::getUserId, userId)
                .eq(KbUserAssistantInfo::getSex, sex)
                .list();
        if (list == null || list.size() == 0) {
            //如果列表为空就自动添加
            List<KbAssistant> defaultlist = kbAssistantService.defaultlist(sex);
            List<KbUserAssistantInfo> kbUserAssistantInfoList = defaultlist.stream()
                    .map(i -> {
                        KbUserAssistantInfo kbUserAssistantInfo = new KbUserAssistantInfo();
                        kbUserAssistantInfo.setUserId(userId);
                        kbUserAssistantInfo.setCreateTime(LocalDateTime.now());
                        kbUserAssistantInfo.setKbAssistantId(i.getId());
                        kbUserAssistantInfo.setKbAssistantName(i.getName());
                        kbUserAssistantInfo.setAssistantUrl(i.getIcon());
                        kbUserAssistantInfo.setSex(sex);
                        kbUserAssistantInfo.setAssistantStyls(i.getOutStyle());
                        return kbUserAssistantInfo;
                    })
                    .collect(Collectors.toList());
            return addList(kbUserAssistantInfoList);
        }
        return list;
    }


    @Override
    public List<KbUserAssistantInfo> addList(List<KbUserAssistantInfo> list) {
        if (list == null || list.size() == 0) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }
        boolean b = saveOrUpdateBatch(list);
        if (b) {
            KbUserAssistantInfo kbUserAssistantInfo = list.get(0);
            return lambdaQuery()
                    .eq(KbUserAssistantInfo::getUserId, kbUserAssistantInfo.getUserId())
                    .eq(KbUserAssistantInfo::getSex, kbUserAssistantInfo.getSex())
                    .list();
        }
        return null;
    }

    @Override
    public List<KbUserAssistantInfo> add(KbUserAssistantInfo kbUserAssistantInfo) {
        String userId = kbUserAssistantInfo.getUserId();
        if (userId == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }
        User user = userService.getUserFormRedisOrDb(userId);
        if (user == null) {
            throw new BusinessException(CommonErrorCode.USER_NOT_EXIST);
        }

        //不是付费会员不让用
//        Integer vipFlag = user.getVipFlag();
//        if (vipFlag == null || vipFlag != CommonConstants.VIP_FLAG_FREE_TOKENS_VIP) {
//            throw new BusinessException(CommonErrorCode.VIP_NOT_VIP);
//        }

        Long customerId = kbUserAssistantInfo.getId();
        Long assistantId = kbUserAssistantInfo.getKbAssistantId();


        if (assistantId == null) {
            //自定义标签
            KbCustomerAssistant customerAssistant = customAssistantService.getById(customerId);
            if (customerAssistant == null) {
                throw new BusinessException(CommonErrorCode.ASSISTANT_NOT_EXIST);
            }
            kbUserAssistantInfo.setKbAssistantId(customerId);
            kbUserAssistantInfo.setType(CommonConstants.KB_ASSISTANT_TYPE_CUSTOMER);
        }else if(assistantId!=null){
            //系统标签
            KbAssistant kbAssistant = kbAssistantService.getById(assistantId);
            if (kbAssistant == null) {
                throw new BusinessException(CommonErrorCode.ASSISTANT_NOT_EXIST);
            }
            kbUserAssistantInfo.setAssistantStyls(kbAssistant.getOutStyle());
            kbUserAssistantInfo.setKbAssistantName(kbAssistant.getName());
            kbUserAssistantInfo.setAssistantUrl(kbAssistant.getIcon());
            kbUserAssistantInfo.setType(CommonConstants.KB_ASSISTANT_TYPE_SYSTEM);
        }else {
            throw new BusinessException(CommonErrorCode.ASSISTANT_NOT_EXIST);
        }

        KbUserAssistantInfo one = lambdaQuery()
                .eq(KbUserAssistantInfo::getUserId, kbUserAssistantInfo.getUserId())
                .eq(KbUserAssistantInfo::getKbAssistantId, assistantId)
                .eq(KbUserAssistantInfo::getSex,user.getSex())
                .eq(KbUserAssistantInfo::getType,kbUserAssistantInfo.getType())
                .one();
        if (one == null) {
            kbUserAssistantInfo.setId(null);
            kbUserAssistantInfo.setCreateTime(LocalDateTime.now());
            kbUserAssistantInfo.setSex(user.getSex());
            boolean isSaveSuccess = save(kbUserAssistantInfo);
            if (!isSaveSuccess) {
                throw new BusinessException(CommonErrorCode.OP_FAIL);
            }
        }
        return getListbyUserId(kbUserAssistantInfo.getUserId(),user.getSex());
    }


    @Override
    public List<KbUserAssistantInfo> delete(KbUserAssistantInfo kbUserAssistantInfo) {
        KbUserAssistantInfo one = lambdaQuery()
                .eq(KbUserAssistantInfo::getUserId, kbUserAssistantInfo.getUserId())
                .eq(KbUserAssistantInfo::getKbAssistantId, kbUserAssistantInfo.getKbAssistantId())
                .eq(KbUserAssistantInfo::getSex,kbUserAssistantInfo.getSex())
                .one();
        if (one != null) {
            boolean isDeleteSuccess = removeById(one.getId());
            if (!isDeleteSuccess) {
                throw new BusinessException(CommonErrorCode.OP_FAIL);
            }
        }
        return getListbyUserId(kbUserAssistantInfo.getUserId(),kbUserAssistantInfo.getSex());
    }

    @Override
    public List<KbUserAssistantInfo> deleteByIds(KbUserAssistantAddAllDto params) {
        List<KbUserAssistantInfo> list = params.getList();
        List<Long> ids = list.stream()
                .map(item -> item.getId())
                .collect(Collectors.toList());
        String userId = params.getUserId();

        KbUserAssistantInfo kbUserAssistantInfo = list.get(0);

        //删除旧数据
        LambdaQueryWrapper<KbUserAssistantInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.in(KbUserAssistantInfo::getId, ids);
        boolean remove = remove(wrapper);
        if (!remove) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }
        return getListbyUserId(userId,kbUserAssistantInfo.getSex());
    }
}
